<?php

declare(strict_types = 1);

namespace App\Traits;

trait Json
{
    protected $http_code = 200;

    public function successJson($data = [], $msg = 'success', $other = [])
    {
        return $this->myAjaxReturn(array_merge(['data' => $data, 'msg' => $msg, 'http_code' => 200], $other));
    }

    public function errorJson($msg = 'error', $http_code = 400, $data = [], $other = [])
    {
        return $this->myAjaxReturn(array_merge(['msg' => $msg, 'http_code' => $http_code, 'data' => $data], $other));
    }
    public function setHttpCode(int $http_code): void
    {
        $this->http_code = 200;
    }

    /**
     * [myAjaxReturn]
     * @author:cnpscy <[2278757482@qq.com]>
     * @chineseAnnotation:API接口返回格式统一
     * @englishAnnotation:
     * @version:1.0
     * @param              [type] $data [description]
     */
    public function myAjaxReturn($data)
    {

        $data['data'] = $data['data'] ?? [];
        if(!isset($data['http_code'])) $data['http_code'] = $this->http_code;
        switch ($data['http_code']){
            case 200:
                $data['status'] = 1;
                break;
            case 400:
                $data['status'] = 0;
                break;
            case 401:
                $data['status'] = -1;
                break;
            case 403:
                $data['status'] = -2;
                break;
        }
        $data['msg'] = $data['msg'] ?? (empty($data['status']) ? '数据不存在！' : 'success');

        return response()->json($data, $data['http_code']);
    }
    //******************************** API  ****************************************************************************

    public function sendApiSuccess($data = [], $code=200,$msg = '请求成功'){

        return $this->ApiReturn([ 'code' => 0,'status' => $code, 'message' => $msg,'data' => $data]);
    }
    public function sendApiError($msg = '请求错误', $code = 1, $data = [], $other = []){

        return $this->ApiReturn(array_merge([ 'code' =>  $code??1,'status' => $code,'message' => $msg, 'data' => $data], $other));
    }
    public function ApiReturn($data)
    {
        $data['status'] = intval($data['status'] ?? (empty($data['status']) ? 500 : 200));
        $data['message'] = $data['message'] ?? (empty($data['message']) ? '数据不存在！' : 'success');
        $data['data'] = $data['data'] ?? [];
        return response()->json($data,  200);
    }
}
